package org.mianshi.eleme;

import com.sun.xml.internal.bind.v2.model.core.EnumLeafInfo;

import java.util.HashSet;
import java.util.Set;

//https://leetcode.cn/problems/linked-list-cycle/
public class 链表是否有环 {

}

/**
 * Definition for singly-linked list.
 * class ListNode {
 * int val;
 * ListNode next;
 * ListNode(int x) {
 * val = x;
 * next = null;
 * }
 * }
 */


//hash表解法
class Solution3 {
    public boolean hasCycle(ListNode head) {
        if (head == null) {
            return false;
        }
        Set<ListNode> sets = new HashSet<>();
        ListNode cur = head;
        while (cur != null) {
            if (sets.contains(cur)) {
                return true;
            } else {
                sets.add(cur);
                cur = cur.next;

            }

        }
        return false;
    }
}


//快慢指针表解法    两个指针，1个快，1个慢，如果有环，那么快的先入环，一定会追上慢的
class Solution4 {
    public boolean hasCycle(ListNode head) {
        if (head == null) {
            return false;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while (fast!=slow){
            if (fast==null||fast.next==null){
                return false;
            }
            fast = fast.next.next;
            slow = slow.next;

        }
        return true;
    }
}
